<?php
/**
 * Created by PhpStorm.
 * User: nightelf
 * Date: 2020/1/9
 * Time: 14:14
 */

namespace App\Http\Controllers\Admin;


use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Http\Model\AdminModel;
use App\Http\Model\AdminRoleModel;
use App\Http\Model\PermissionModel;
use App\Http\Model\ProfessionModel;
use App\Http\Model\RolePermissionModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdminController extends Controller
{
    const  COMPANY = 1;
    const  PROJECT = 2;
    /**
     * 获取账号的角色信息
     * @param $adminId
     * @return mixed
     */
    public function getRole($adminId)
    {
        $adminRoleModel = new AdminRoleModel();
        $adminRole = $adminRoleModel->getAdminRole($adminId);
        return $adminRole;
    }

    /**
     * 获取账号的权限
     * @param $adminId
     * @param $roleId
     * @param $isProject
     * @return mixed
     */
    public function getPermission($adminId, $roleId, $isProject)
    {
        $adminPermission = array();
        if ($adminId == 1){
            $permissionModel = new PermissionModel();
            $adminPermission = $permissionModel->lists(['isProject'=>$isProject]);
        }else{
            if ($roleId != 0) {
                $rolePermissionModel = new RolePermissionModel();
                $adminPermission = $rolePermissionModel->getPermission($roleId);
            }
        }

        return $adminPermission;
    }

    /**
     * @param $permission
     * @return array
     */
    public function getMenu($permission)
    {
        $menuLists = [];
        foreach($permission as $p){
            if ($p->type == 1){
                $menuLists[] = $p;
            }
        }
        if (!empty($menuLists)){
            return $this->listToTree($menuLists);
        }else{
            return [];
        }
    }

    /**
     * 修改密码
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function changePwd(Request $request)
    {
        $rules = [
            'adminId' => 'required|integer',
//            'oldPwd' => 'required',
            'password' => 'required|alpha_num|between:6,16',
        ];
        $message = [
            'adminId.required' => '获取用户参数失败',
            'adminId.integer' => '用户参数类型错误',
//            'oldPwd.required' => '请填写原密码',
            'password.required' => '请输入新密码',
            'password.alpha_num' => '新密码只允许包含字母或数字',
            'password.between' => '新密码长度必须设置为 :min 到 :max 位',
        ];
        $param = $request->only('adminId','oldPwd','password');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminModel = new AdminModel();
            //验证原密码
//            $oldPwd = $this->encrypt($param['oldPwd']);
            $adminInfo = $adminModel->info(['id' => $param['adminId']]);
            //验证原密码
//            if ($adminInfo['password'] != $oldPwd){
//                throw new ApiException('原密码错误',120102);
//            }
            //保存新密码
            $result = $adminModel->update(['id' => $param['adminId']],['password' => $this->encrypt($param['password'])]);
            if ($result < 1) {
                throw new ApiException('修改密码失败',120103);
            }
        } else {
            throw new ApiException($validator->errors()->first(),120101);
        }
        return $this->ajaxResult($this->code, $this->msg);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function lists(Request $request)
    {
        $rules = [
            'projectId' => 'nullable|integer',
            'length' => 'nullable|integer|in:10,20,50',
            'page' => 'nullable|integer|min:0',
        ];
        $message = [
            'projectId.integer' => '项目参数类型错误',
            'length.integer' => '记录条数参数类型错误',
            'length.in' => '记录条数参数值不正确',
            'page.integer' => '页码参数类型错误',
            'page.min' => '页码参数值不小于:min',
        ];
        $param = $request->only('projectId','page','length','search');
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminModel = new AdminModel();
            $professionModel = new ProfessionModel();
            $lists = $adminModel->lists($param);
            foreach ($lists as $info) {
                $professionList = json_decode($info->professionId, true);
                if (count($professionList) > 0) {
                    $profession = '';
                    foreach ($professionList as $i) {
                        $tmp = $professionModel->info(['id' => $i]);
                        if (!empty($tmp)){
                            $profession.= $tmp['name'].',';
                        }
                    }
                    $profession = substr($profession,0,-1);
                }else{
                    $profession = '全部';
                }
                $info->professionName = $profession;
            }
            $countLists = $adminModel->countLists($param);
            $this->data = $this->tableFormat($lists,$countLists);
        } else {
            throw new ApiException($validator->errors()->first(),120201);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * 添加管理员
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function add(Request $request)
    {
        $rules = [
            'username' => 'required',
            'roleId' => 'required|integer',
            'name' => 'required',
            'projectId' => 'required|integer',
            'professionId' => 'required',
            'phone' => 'required',
        ];
        $message = [
            'username.required' => '请填写用户名',
            'roleId.required' => '请选择角色',
            'roleId.integer' => '角色参数类型错误',
            'name.required' => '请填写姓名',
            'projectId.required' => '请选择账号所属项目',
            'projectId.integer' => '项目参数类型错误',
            'professionId.required' => '请选择账号负责工种',
            'phone.required' => '请填写联系方式',
        ];
        $param = $request->only(['username', 'roleId', 'name', 'projectId', 'phone', 'professionId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminModel = new AdminModel();
            $info = $adminModel->checkRepeat(['username' => $param['username'], 'name' => $param['name']]);
            if (!empty($info)) {
                throw new ApiException('不能建立相同用户名或姓名的账号',120302);
            }
            $param['password'] = $this->encrypt('123456');
            $result = $adminModel->addAdmin($param);
            if (!$result) {
                throw new ApiException($result,120303);
            }
        } else {
            throw new ApiException($validator->errors()->first(),120301);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * 管理员详情
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function info(Request $request)
    {
        $rules = [
            'id' => 'required|integer',
        ];
        $message = [
            'id.required' => '获取管理员参数失败',
            'id.integer' => '管理员参数类型错误',
        ];
        $param = $request->only(['id']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminModel = new AdminModel();
            $professionModel = new ProfessionModel();
            $info = $adminModel->info(['id'=>$param['id']]);
            $professionList = json_decode($info['professionId'], true);
            if (count($professionList) > 0) {
                $profession = '';
                foreach ($professionList as $i) {
                    $tmp = $professionModel->info(['id' => $i]);
                    if (!empty($tmp)){
                        $profession.= $tmp['name'].',';
                    }
                }
                $profession = substr($profession,0,-1);
            }else{
                $profession = '全部';
            }
            $info['professionName'] = $profession;
            $this->data = $info;
        } else {
            throw new ApiException($validator->errors()->first(),120401);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function edit(Request $request)
    {
        $rules = [
            'id' => 'required|integer',
            'username' => 'required',
//            'roleId' => 'required|integer',
            'name' => 'required',
            'projectId' => 'required|integer',
            'professionId' => 'required',
            'phone' => 'required',
        ];
        $message = [
            'id.required' => '获取用户参数失败',
            'id.integer' => '用户参数类型错误',
            'username.required' => '请填写用户名',
//            'roleId.required' => '请选择角色',
//            'roleId.integer' => '角色参数类型错误',
            'name.required' => '请填写姓名',
            'projectId.required' => '请选择账号所属项目',
            'projectId.integer' => '项目参数类型错误',
            'professionId.required' => '请选择账号负责工种',
            'professionId.integer' => '工种参数类型错误',
            'phone.required' => '请填写联系方式',
        ];
        $param = $request->only(['id', 'username', 'name', 'projectId', 'phone', 'professionId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminModel = new AdminModel();
            $id = $param['id'];unset($param['id']);
            $result = $adminModel->update(['id'=>$id],$param);
            if (!$result) {
                throw new ApiException($result,120502);
            }
        } else {
            throw new ApiException($validator->errors()->first(),120501);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function editStatus(Request $request)
    {
        $rules = [
            'id' => 'required|integer',
            'status' => 'required|integer|in:0,1',
        ];
        $message = [
            'id.required' => '获取管理员参数失败',
            'id.integer' => '管理员参数类型错误',
            'status.required' => '获取管理员状态失败',
            'status.integer' => '管理员状态参数类型错误',
            'status.in' => '管理员状态参数不正确',
        ];
        $param = $request->only(['id', 'status']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminModel = new AdminModel();
            $adminModel->update(['id'=>$param['id']], ['status' => $param['status']]);
        } else {
            throw new ApiException($validator->errors()->first(),120601);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function setRole(Request $request)
    {
        $rules = [
            'adminId' => 'required|integer',
            'roleId' => 'required|integer',
        ];
        $message = [
            'adminId.required' => '获取管理员参数失败',
            'adminId.integer' => '管理员参数类型错误',
            'roleId.required' => '请选择角色',
            'roleId.integer' => '角色参数类型错误',
        ];
        $param = $request->only(['adminId', 'roleId']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminRoleModel = new AdminRoleModel();
            $adminRoleModel->delete(['adminId' => $param['adminId']]);
            $adminRoleModel->insert($param);
        } else {
            throw new ApiException($validator->errors()->first(),120701);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws ApiException
     */
    public function selectLists(Request $request)
    {
        $rules = [
            'projectId' => 'nullable|integer',
        ];
        $message = [
            'projectId.integer' => '管理员参数类型错误',
        ];
        $param = $request->only(['projectId','search']);
        $validator = Validator::make($param, $rules, $message);
        if ($validator->passes()) {
            $adminModel = new AdminModel();
            $this->data = $adminModel->selectLists($param);
        } else {
            throw new ApiException($validator->errors()->first(),120801);
        }
        return $this->ajaxResult($this->code, $this->msg, $this->data);
    }
}